package com.jinglvhuanjing.app.base;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.example.x6.serial.SerialPort;
import com.jinglvhuanjing.app.GarbageDisposalActivity;
import com.jinglvhuanjing.app.LoginActivity;
import com.jinglvhuanjing.app.utils.ByteUtil;
import com.jinglvhuanjing.app.utils.Constants;
import com.jinglvhuanjing.app.utils.ExecutorProcessPool;
import com.jinglvhuanjing.app.utils.LOG;
import com.jinglvhuanjing.app.utils.SerialMsgHandler;
import com.jinglvhuanjing.app.utils.SingletonSerl;
import com.jinglvhuanjing.app.utils.SpUtils;
import com.jinglvhuanjing.app.utils.StringUtils;

import java.io.IOException;

public abstract class InstructionActivity extends BaseActivity{

    protected SingletonSerl singletonSerl;

    protected int sleepTime = 200;// 报文指令间隔200ms

    protected int closeTime = 50;// 关门延迟时间 50ms

    private boolean onResume = false;

    /*** 解析收到的登录信息 ***/
    protected Handler mHandlerLogin = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SerialMsgHandler.CONNECT3:
                    LOG.e(TAG, "字符串："+msg.obj+"--onResume="+onResume);
                    if(onResume){
                        // 解析数值
                        String data = (String) msg.obj;
                        if(data.length()>22){
                            data = data.substring(0, 22);
                        }
                        LOG.e(TAG, "字符串："+data);
                        String phone = ByteUtil.hexToAscii(data);
                        LOG.e(TAG, "字符串转Ascii："+phone);
                        String account = SpUtils.getString(getApplicationContext(), Constants.ACCOUNT);
                        LOG.e(TAG, "account="+account+"-phone="+phone+"-"+(!StringUtils.isEmpty(phone)&&!StringUtils.isEmpty(account)&&account.contains(phone)));
                        if(!StringUtils.isEmpty(phone)&&!StringUtils.isEmpty(account)&&account.contains(phone)){
                            GarbageDisposalActivity.startActivity(InstructionActivity.this);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void initView(Bundle savedInstanceState) {
        String sleep = SpUtils.getString(getApplicationContext(), Constants.INTERVAL_TIME, "200");
        String close = SpUtils.getString(getApplicationContext(), Constants.CLOSE_TIME, "50");
        sleepTime = Integer.valueOf(StringUtils.isEmpty(sleep)?"200":sleep);
        closeTime = Integer.valueOf(StringUtils.isEmpty(close)?"50":close);
        try {
            singletonSerl = SingletonSerl.getInstance();
        } catch (IOException e) {
            e.printStackTrace();
            LOG.e(TAG, "SingletonSerl 初始化 错误:" + e.toString());
        }
    }

    protected void setOnResume(boolean onResume){
        this.onResume = onResume;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    protected void write_lunxun() {
        if (hasSingletonSerl()) {
            ExecutorProcessPool.getInstance().execute(() -> {
                lunxun();
            });
        }
//        test();
    }

    protected void lunxun(){
        clear();

        for (int i = 0; i < singletonSerl.bytes_tk.length; i++) {
            write(singletonSerl.getTK_(ByteUtil.hexByteToString(singletonSerl.bytes_tk[i])));
        }

        if (hasSingletonSerl()) {
            LOG.e(SerialMsgHandler.TAG, "启动读取功能");
            SerialMsgHandler.getInstance().setStartListener(true, mHandlerIn);
        }
    }

    protected void test() {
        LOG.e(TAG, "========================="+System.currentTimeMillis());
        sleep();
        byte[] _254 = ByteUtil.hexStringToBytes("FE");
        int _254_10 = ByteUtil.hexStringToInt("640E");
        String _254_Str = ByteUtil.hexBytesToString(new byte[]{(byte) 0x01, (byte) 0x03, (byte) 0x00, (byte) 0x0A, (byte) 0x00, (byte) 0x08});
        String _254_Str_ = ByteUtil.hexByteToString((byte) 0xFE);
        LOG.e(TAG, "_254_10=" + _254_10 + "--_254_Str=" + _254_Str + "--" + _254_Str_);
        StringBuffer bufferFirst = singletonSerl.openDoorFirstOrEnd("01", true);
        StringBuffer bufferEnd = singletonSerl.openDoorFirstOrEnd("01", false);
        LOG.e(TAG, "bufferFirst="+bufferFirst.toString());
        LOG.e(TAG, "bufferEnd="+bufferEnd.toString());
        sleep();
        LOG.e(TAG, "========================="+System.currentTimeMillis());
    }

    Handler mHandlerIn = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SerialMsgHandler.CONNECT2:
                    String obj = (String) msg.obj;
                    LOG.e(SerialMsgHandler.TAG, "读取内容:" + obj);
                    if(!StringUtils.isEmpty(obj)){
                        byte[] bytes_ = ByteUtil.hexStringToBytes(obj);
                        if(bytes_!=null && bytes_.length > 1){
                            // 03 功能码，保存对应投口的类型
                            if(bytes_[1] == SingletonSerl.byte_gnm_type && bytes_.length>20){
                                String dz = ByteUtil.hexByteToString(bytes_[0]);
                                String type = ByteUtil.hexByteToString(bytes_[4]);
                                int jlz = ByteUtil.hexStringToInt(ByteUtil.hexBytesToString(new byte[]{bytes_[5],bytes_[6]}));
                                LOG.e(TAG, "投口地址："+dz+
                                        "--投口类型："+type+
                                        "--距离值："+jlz);
                                // key为地址存储投口类型
                                SpUtils.putString(getApplicationContext(),
                                        SingletonSerl.tk_string_start+dz,
                                        type);
                                // key为地址存储投口距离值
                                SpUtils.putInt(getApplicationContext(),
                                        SingletonSerl.tk_jlz_string_start+dz,
                                        jlz);
                            }
                        }else{
                            LOG.e(SerialMsgHandler.TAG, "读取内容 空");
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    protected void clear(){
        String s1 = ByteUtil.hexByteToString(SingletonSerl.byte_tk1);
        String s2 = ByteUtil.hexByteToString(SingletonSerl.byte_tk2);
        String s3 = ByteUtil.hexByteToString(SingletonSerl.byte_tk3);
        String s4 = ByteUtil.hexByteToString(SingletonSerl.byte_tk4);
        String s5 = ByteUtil.hexByteToString(SingletonSerl.byte_tk5);

        // key为地址存储投口类型
        SpUtils.putString(getApplicationContext(),
                SingletonSerl.tk_string_start+s1,
                "");
        SpUtils.putString(getApplicationContext(),
                SingletonSerl.tk_string_start+s2,
                "");
        SpUtils.putString(getApplicationContext(),
                SingletonSerl.tk_string_start+s3,
                "");
        SpUtils.putString(getApplicationContext(),
                SingletonSerl.tk_string_start+s4,
                "");
        SpUtils.putString(getApplicationContext(),
                SingletonSerl.tk_string_start+s5,
                "");

        // key为地址存储投口距离值
        SpUtils.putInt(getApplicationContext(),
                SingletonSerl.tk_jlz_string_start+s1,
                0);
        // key为地址存储投口距离值
        SpUtils.putInt(getApplicationContext(),
                SingletonSerl.tk_jlz_string_start+s2,
                0);
        // key为地址存储投口距离值
        SpUtils.putInt(getApplicationContext(),
                SingletonSerl.tk_jlz_string_start+s3,
                0);
        // key为地址存储投口距离值
        SpUtils.putInt(getApplicationContext(),
                SingletonSerl.tk_jlz_string_start+s4,
                0);
        // key为地址存储投口距离值
        SpUtils.putInt(getApplicationContext(),
                SingletonSerl.tk_jlz_string_start+s5,
                0);
    }

    protected void write(StringBuffer buffer) {
        String end = SingletonSerl.getCRC3(ByteUtil.hexStringToBytes(buffer.toString()));
        LOG.e(TAG, "write crc16:" + end);
        buffer.append(end);
        LOG.e(TAG, "end=" + buffer.toString());
        if (hasSingletonSerl()) {
            singletonSerl.writeHexString(buffer.toString());
            LOG.e(TAG, "write 结束");
            sleep();
        }
    }

    protected void sleep(){
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录串口对象判断
     *
     * @return
     */
    protected boolean hasSingletonSerlLogin() {
        if (singletonSerl == null) {
            try {
                singletonSerl = SingletonSerl.getInstance();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (singletonSerl != null) {
            SerialPort serialPort = singletonSerl.getSerialPortConnect2();
            if (serialPort != null) {
                return true;
            }
        }
        return false;
    }

    /**
     * 非登录串口对象判断
     *
     * @return
     */
    protected boolean hasSingletonSerl() {
        if (singletonSerl == null) {
            try {
                singletonSerl = SingletonSerl.getInstance();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LOG.e(TAG, "singletonSerl:"+(singletonSerl!=null));
        if (singletonSerl != null) {
            SerialPort serialPort = singletonSerl.getSerialPortConnect3();
            if (serialPort != null) {
                return true;
            }
        }
        return false;
    }

    /**
     * 不足位数，前面补充0
     * @param bw
     * @param length 总体长度
     * @return
     */
    protected String String_0(String bw, int length){
        if(bw.length()==length){
            return bw;
        }
        for(int i=0; i<=length-bw.length();i++){
            bw = "0"+bw;
        }
        return bw;
    }
}
